package 链表高频题和必备技巧;

/**
 * @author ljb
 * @version 1.0
 * @Date 2024/12/11
 */
// 返回两个无环链表相交的第一个节点
// 测试链接 : https://leetcode.cn/problems/intersection-of-two-linked-lists/
public class Code01_IntersectionOfTwoLinkedLists {

    public class ListNode{
        public int val;
        public ListNode next;
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
            return null;
        }
        ListNode a = headA, b = headB;
        int diff = 0;
        while(a.next != null){
            a = a.next;
            diff++;
        }
        while(b.next != null){
            b = b.next;
            diff--;
        }
        if(a != b){
            return null;
        }
        //让a节点指向较长的那个链表
        if(diff >= 0){
            a = headA;
            b = headB;
        }else {
            a = headB;
            b = headA;
        }
        diff = Math.abs(diff);
        while(diff != 0){
            a = a.next;
            diff--;
        }
        while(a != b){
            a = a.next;
            b = b.next;
        }
        return a;
    }
}
